package com.kaibes.module.file.local.listener;

import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.kaibes.module.file.local.db.FileInfoService;
import com.kaibes.module.file.local.db.FileMark;
import com.kaibes.module.file.local.db.FileMarkService;
import com.kaibes.orm.core.listener.DeleteListener;
import com.kaibes.orm.curd.Delete;
import com.kaibes.orm.spring.OrmListener;

@OrmListener(service = FileMarkService.class)
public class FileMarkDeleteListener implements DeleteListener {
    
    @Autowired
    private FileMarkService fileMarkService;
    @Autowired
    private FileInfoService fileInfoService;
    
    private ThreadLocal<List<FileMark>> threadLocal = new ThreadLocal<>();

    @Override
    public void beforeDelete(Delete delete) throws SQLException {
        List<FileMark> fileMarkList = fileMarkService.list(delete.getQueries());
        if (!fileMarkList.isEmpty()) {
            threadLocal.set(fileMarkList);
        }
    }
    
    @Override
    public void afterDelete(Delete delete, int count) throws SQLException {
        List<FileMark> fileMarks = threadLocal.get();
        if (fileMarks != null) {
            threadLocal.set(null);
            for (FileMark fileMark : fileMarks) {
                if (!fileMarkService.hasFileByFileInfoId(fileMark.getFileInfoId())
                        && fileInfoService.hasByID(fileMark.getFileInfoId())) {
                    fileInfoService.removeById(fileMark.getFileInfoId());
                }
            }
        }
    }
    
}
